import TabsDropComponent from '@/components/TabsDropComponent'
import ListEmpty from '@/components/antd-comp/empty'
import ModalComponent from '@/components/antd-comp/modal/ModalComponent'
import TableGrid from '@/components/antd-comp/table'
import { columnsProps } from '@/components/antd-comp/table/constants'
import ThemeBtn from '@/components/antd-comp/theme-btn'
import FouterPage from '@/components/fouter-page'
import InputAntDef from '@/components/input/InputAntDef'
import { workflowPublishListApi } from '@/pages/workflow/API'
import { Func } from '@/permissions/constants'
import { useDictStore } from '@/store/dictStore'
import { useFuncsStore } from '@/store/funcStore'
import { useTable } from '@/util/hook'
import { Tooltip } from 'antd'
import { useEffect, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import '../../FileLibPage/css/index.css'
import '../css/styles.css'
const getUniqueKey = (record: any) => record.id
const WorkFlowDia = ({ open, setOpen, addWorkFlow, flow_list }) => {
  /**
   * 功能权限限制
   */
  const { hasFuncPermission } = useFuncsStore()
  /* 取消 */
  const handleCancel = (e: React.MouseEvent<HTMLElement>) => {
    setOpen(false)
  }
  const [allList, setAllList] = useState([])
  useEffect(() => {
    setAllList(flow_list)
  }, [flow_list])
  const { t } = useTranslation()

  const [num, setNum] = useState(0) as any
  const [name, setName] = useState(undefined)

  const linkToCreate = (path, type) => {
    window.open(path, '_blank', 'noreferrer')
  }

  // 类型选择
  const [typeList, setTypeList] = useState([])
  const typeMap = useRef({})
  const { loadDictOptions } = useDictStore()
  const loadTypeList = (type = 'category') => {
    loadDictOptions(type).then(res => {
      if (res) {
        res.unshift({
          id: 0,
          label: '全部类型',
          value: 'all'
        })
        setTypeList(res)
        const typeInfo = {}
        res.forEach(type => {
          typeInfo[type.id] = type.label
        })
        typeMap.current = typeInfo
      } else {
        setTypeList([
          {
            id: 0,
            label: t('all')
          }
        ])
      }
    })
  }

  useEffect(() => {
    //loadTypeList()
  }, [])

  const {
    page,
    pageSize,
    data: datalist,
    total,
    loading,
    setPage,
    filterData
  } = useTable({ pageSize: 15 }, param => workflowPublishListApi(param.page, param.pageSize, name, num || ''))

  const seleCarFun = (data, id) => {
    setNum(id)
    filterData({ name, type: id })
  }

  const beforeSearch = val => {
    setName(val)
    filterData({ name: val, type: num })
  }

  const handleTypeInfo = val => {
    return typeMap.current[val] || '--'
  }

  // 定义tableColumns
  const tableColumns: columnsProps[] = [
    {
      dataIndex: 'name',
      title: '工作流',
      width: 260,
      fixed: 'left',
      render: (text, record, _index) => (
        <div className="flexRowStart">
          {record.logo && record.logo !== 'None' && (
            <img
              src={record.logo}
              alt="icon"
              style={{
                height: '36px',
                width: '36px',
                margin: '0 8px 0 0',
                borderRadius: '4px',
                display: 'inline'
              }}
            />
          )}
          <div className="flexCol skills_page_oneCase">
            <Tooltip title={text}>
              <span className="fileLibPage_name domOverflowEllip">{text}</span>
            </Tooltip>
            <Tooltip title={record.description}>
              <span className="fileLibPage_description domOverflowEllip">{record.description}</span>
            </Tooltip>
          </div>
        </div>
      ),
      ellipsis: {
        showTitle: false
      },
      className: 'filelib_name_column'
    },
    // {
    //   dataIndex: 'category_code',
    //   title: t('lib.type'),
    //   width: 100,
    //   render: (text, _record, _index) => handleTypeInfo(text)
    // },
    {
      dataIndex: 'user_name',
      title: t('lib.createUser'),
      width: 140,
      render: (text, _record, _index) => {
        return (
          <div className="flexRowStart">
            <Tooltip title={text}>
              <span className="fileLibPage_user_name domOverflowEllip">{text}</span>
            </Tooltip>
          </div>
        )
      }
    },
    {
      dataIndex: 'create_time',
      title: t('createTime'),
      width: 180,
      render: (text, _record, _index) => text?.replace('T', ' ')
    },
    {
      dataIndex: 'update_time',
      title: t('updateTime'),
      width: 180,
      render: (text, _record, _index) => text?.replace('T', ' ')
    },
    {
      dataIndex: 'operation',
      title: t('operations'),
      fixed: 'right',
      width: 150,
      render: (_text, record, _index) => (
        <div className="flexRowStart ml-[-16px] bg-inherit">
          <div
            className="migu-font-400 cursonCase ml-[16px] text-[#062FF8]"
            onClick={() => {
              linkToCreate(`/workflow/${record.id}`, 'create')
            }}
          >
            {t('lib.details')}
          </div>
          <div
            style={{
              background: '#5964F3',
              padding: '2px 12px',
              borderRadius: '6px',
              boxSizing: 'border-box',
              color: '#FFFFFF',
              fontSize: '12px',
              fontWeight: '400'
            }}
            onClick={() => {
              // 使用 some 方法来检查 record 是否存在于 allList 中
              if (allList.some(item => item.id === record.id)) {
                return
              }
              addWorkFlow(record)
            }}
            className={
              allList.some(item => item.id === record.id) ? 'noAdd_cursonCase ml-[16px]' : 'cursonCase ml-[16px]'
            }
          >
            {allList.some(item => item.id === record.id) ? '已添加' : '添加'}
          </div>
          {/* 为了实现右侧fix时border-radius额外增加的遮罩层 */}
          <div className="common-table-right-fixed-layer2">{''}</div>
          <div className="common-table-right-fixed-layer3">{''}</div>
        </div>
      )
    }
  ]

  // table的分页、排序、筛选变化时触发
  const handleTableChange = (values: any) => {
    console.log('values', values)
  }

  return (
    <>
      <ModalComponent
        width={1200}
        className="modal_antcomp_case Application_FailDiaCont max-h-[50%]"
        title={'添加工作流'}
        open={open}
        style={{ top: '10%' }}
        onCancel={handleCancel}
        footer={[]}
        content={
          <div className="flexRowStart caseOverFlowY" style={{ height: '70vh' }}>
            {loading && (
              <div className="absolute left-0 top-0 z-10 flex h-full w-full items-center justify-center bg-[rgba(255,255,255,0.6)] dark:bg-blur-shared">
                <span className="loading loading-infinity loading-lg"></span>
              </div>
            )}
            <div className="filelib-container rounded-[6px]" style={{ margin: '0 20px !important', top: '10px' }}>
              <div className="flexRowJustBet flex py-[24px]" style={{ background: 'white' }}>
                <div className="flexRowStart">
                  <div style={{ marginRight: '16px' }}>
                    <TabsDropComponent
                      backColor={'#F5F7FB'}
                      list={typeList}
                      num={num}
                      tabsDropFun={seleCarFun}
                    ></TabsDropComponent>
                  </div>
                  <InputAntDef
                    searchFun={e => {
                      beforeSearch(e.target.value)
                    }}
                    placeholder={t('lib.enterName')}
                  ></InputAntDef>
                </div>
                {/* <div className=" flex items-center justify-end gap-4">
                  <ThemeBtn
                    className="migu-font-600 h-[36px] w-[92px]"
                    onClick={() => {
                      if (!hasFuncPermission([Func.workflow.add])) {
                        return
                      }
                      linkToCreate('/workflow', 'create')
                    }}
                  >
                    {t('create')}
                  </ThemeBtn>
                </div> */}
              </div>
              <div
                style={{
                  height: 'calc(100% - 150px)',
                  maxHeight: 'calc(100% - 150px)',
                  paddingBottom: '50px',
                  boxSizing: 'border-box'
                }}
                className=" overflow-y-scroll scrollbar-hide"
              >
                <TableGrid
                  tableInfo={{
                    tableData: datalist,
                    tableColumns,
                    getUniqueKey, // 唯一id
                    // tableIsLoading: loading,
                    getTableChangeValues: handleTableChange, // 获取table事件
                    // scrollHeight: 'calc(100vh - 294px)',
                    scrollHeight: 'calc(70vh - 200px)',
                    scrollWidth: 1160
                  }}
                  emptyComponent={
                    !loading && !datalist?.length ? (
                      <ListEmpty style={{ height: 'calc(100vh - 314px)', margin: 0 }} />
                    ) : (
                      <div style={{ height: 'calc(100vh - 314px)', background: '#ffffff', margin: 0 }}></div>
                    )
                  }
                />
              </div>
              {/* fouter */}
              {!loading && datalist?.length > 0 && (
                <FouterPage
                  className="filelib-bottom-box filelib-gray-text rounded-[6px]"
                  style={{ background: '#FFFFFF', height: '68px', marginBottom: '-10px' }}
                  page={page}
                  pageSize={pageSize}
                  total={total}
                  setPage={newPage => setPage(newPage)}
                ></FouterPage>
              )}
            </div>
          </div>
        }
      ></ModalComponent>
    </>
  )
}

export default WorkFlowDia
